const app = getApp();
let plugin = null;
try {
  plugin = requirePlugin("sdkPlugin").AiLink // 插件输出的页面加工函数 
} catch (error) {
  console.log(error)
}

function inArray(arr, key, val) {
  if (!arr || !arr.length || typeof arr != 'object' || !Array.isArray(arr)) {
    return -1
  }
  for (let i = 0; i < arr.length; i++) {
    if (!key) {
      if (arr[i] == val) {
        return i
      }
    } else if (arr[i][key] === val) {
      return i
    }
  }
  return -1;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer, split) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join(split);
}
module.exports = Behavior({
  data: {
    bluetoothEnabled: false,
    devices: [],
    connected: false
  },
  methods: {
    // showBule() {
    //   this.data.devices = [];
    //   wx.getBluetoothDevices({
    //     success: (res) => {
    //       if (res.devices.length > 0) {
    //         console.log(this.data.devices, res.devices)
    //         this.data.devices = [...res.devices, ...this.data.devices]
    //         this.setData({
    //           devices: this.data.devices
    //         })
    //       }
    //     }
    //   })
    // },
    delete(e){
      for(let i =0;i<this.data.devices.length;i++){
        if(this.data.devices[i].id == e.currentTarget.dataset.item.id){
          this.data.devices.splice(i,1);
        }
      }
      this.setData({
        devices:this.data.devices
      })
    },
    closeBluetoothAdapter() {
      wx.closeBluetoothAdapter()
      this._discoveryStarted = false
    },
    // 初始化蓝牙模块
    openBluetoothAdapter() {

      wx.openBluetoothAdapter({
        success: (res) => {
          console.log('openBluetoothAdapter success', res)
          this.setData({
            bluetoothEnabled: true
          })
          this.startBluetoothDevicesDiscovery()
        },
        fail: (err) => {
          console.log(err)
          if (err.errCode === 10001) {
            wx.showToast({
              title: '请打开蓝牙',
              icon: "none"
            })
            wx.onBluetoothAdapterStateChange((resa) => {
              console.log('onBluetoothAdapterStateChange', resa)
              if (resa.available) {
                this.startBluetoothDevicesDiscovery()
              }
            })
          } else {
            wx.showToast({
              title: err.errMsg,
              icon: "none"
            })
          }
        }
      })
    },
    // 开始搜寻附近的蓝牙外围设备
    startBluetoothDevicesDiscovery() {
      // if (this._discoveryStarted) {
      //   return
      // }
      this._discoveryStarted = true;
      wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        services: [
          "0000FFE0-0000-1000-8000-00805F9B34FB",
          // "F0A0", // BM30广播模块需加上，如使用连接模块可忽略
        ],
        success: (res) => {
          console.log('startBluetoothDevicesDiscovery success', res)
          this.onBluetoothDeviceFound()
        },
        fail: (err) => {
          console.log(err)
        }
      })
    },
    // 监听寻找到新设备的事件
    onBluetoothDeviceFound() {
      wx.onBluetoothDeviceFound((res) => {
        res.devices.forEach(device => {
          if (!device.name && !device.localName) {
            return
          }
          const foundDevices = this.data.devices;
          // console.log(foundDevices, device.deviceId)
          const idx = inArray(foundDevices, 'deviceId', device.deviceId)
          let data = {}
          let buff = device.advertisData.slice(-6)
          device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址，这是由于iOS不直接返回mac地址
          let tempMac = Array.from(device.mac)
          tempMac.reverse()
          device.macAddr = ab2hex(tempMac, ':').toUpperCase()
          // }
          // console.log(this.data.devices)

          if (idx === -1) {
            data[`devices[${foundDevices.length}]`] = device
          } else {
            data[`devices[${idx}]`] = device
          }
          this.setData(data)
          if (this.data.devices.length > 1) {
            this.setData({
              devices: this.process(this.data.devices)
            })
          }
        })
      })
    },
    closeBLEConnection(e) {
      let dataSet = e.currentTarget.dataset;
      let did = dataSet.deviceId;
      wx.showModal({
        title: '',
        content: '是否确认解绑',
        complete: (res) => {
          if (res.confirm) {
            wx.closeBLEConnection({
              deviceId: did,
            })
            this.data.deviceId = '';
            wx.setStorageSync('deviceId', "")
            this.setData({
              connected: false,
              chs: [],
            })
            this.closeBluetoothAdapter();
            this.openBluetoothAdapter();
          }
        }
      })
    },
    // 连接低功耗蓝牙设备
    createBLEConnection(e) {
      console.log(e)
      this._connLoading = true
      wx.showLoading({
        title: '连接中',
      })
      // setTimeout(() => {
      //   if (this._connLoading) {
      //     this._connLoading = false
      //     wx.hideLoading()
      //   }
      // }, 6000)
      const ds = e.currentTarget.dataset
      const index = ds.index
      // 保存当前连接的设备，注意不能从wxml的dataset中直接返回该对象，因为ArrarBuffer类型的数据无法保留
      this._device = this.data.devices[index]
      console.log(this._device, ds.deviceId)
      const deviceId = ds.deviceId
      const name = ds.name
      this.mac = ds.mac
      wx.createBLEConnection({
        deviceId,
        success: (res) => {
          this.setData({
            connected: true,
            name,
            deviceId,
          })
          console.log("createBLEConnection:success", res)
          // wx.stopBluetoothDevicesDiscovery()
          this.onBLEConnectionStateChange();
          this.getBLEDeviceServices(deviceId);
          this.bindling(this.data.deviceId, this.mac ? this.mac : '');
          wx.setStorageSync('deviceId', deviceId)
        },
        fail: res => {
          console.log(res, '连接失败')
          this._connLoading = false
          wx.hideLoading()
          wx.showToast({
            title: '连接失败',
            icon: 'none'
          })
        },
        complete: ()=>{
          if (this._connLoading) {
            this._connLoading = false
            wx.hideLoading()
          }
        }
      })
      // 连接上设备就可以停止蓝牙搜索，减少功耗。
      // this.stopBluetoothDevicesDiscovery()
    },
    // 停止搜寻附近的蓝牙外围设备
    stopBluetoothDevicesDiscovery() {
      wx.stopBluetoothDevicesDiscovery()
    },
    // 获取蓝牙设备的 serviceId
    getBLEDeviceServices(deviceId) {
      wx.getBLEDeviceServices({
        deviceId,
        success: (res) => {
          for (let i = 0; i < res.services.length; i++) {
            if (res.services[i].isPrimary && res.services[i].uuid.indexOf('FFE0') > -1) {
              this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
              return
            }
          }
        }
      })
    },
    // 获取蓝牙设备某个服务中所有特征值(characteristic)
    getBLEDeviceCharacteristics(deviceId, serviceId) {
      this._deviceId = deviceId
      this._serviceId = serviceId
      this._device.serviceId = serviceId

      wx.getBLEDeviceCharacteristics({
        deviceId,
        serviceId,
        success: (res) => {
          console.log('getBLEDeviceCharacteristics success', res.characteristics)

          // 这部分功能在插件的 initPlugin 中已实现，如需用到其中的 uuid 也可取消注释
          // let uuid1, uuid2, uuid3;
          for (let i = 0; i < res.characteristics.length; i++) {
            let item = res.characteristics[i]
            if (item.uuid.indexOf('0000FFE1') != -1) {
              this.uuid1 = item.uuid //下发数据
            } else if (item.uuid.indexOf('0000FFE2') != -1) {
              this.uuid2 = item.uuid //监听数据
            } else if (item.uuid.indexOf('0000FFE3') != -1) {
              this.uuid3 = item.uuid //写入设置
            }
          }
          // 打开监听
          wx.notifyBLECharacteristicValueChange({
            deviceId,
            serviceId,
            characteristicId: this.uuid2,
            state: true,
          })
          // wx.notifyBLECharacteristicValueChange({
          //   deviceId,
          //   serviceId,
          //   characteristicId: this.uuid3,
          //   state: true,
          // })

          // 初始化插件
          plugin.initPlugin(res.characteristics, this._device)

          wx.onBLECharacteristicValueChange((characteristic) => {
            // console.log(characteristic.value)
            // 解析特征值，返回解密后的数据
            let bleData = plugin.parseBleData(characteristic.value)
            // console.log(bleData, bleData.status, '监听设备返回')
            // console.log('sasdwwwwwww', bleData)
            if (bleData.status == 0) {
              console.log("握手成功")
              this._connLoading = false
              wx.hideLoading()
              app.tips('连接成功');
              setTimeout(() => {
                wx.navigateBack({
                  url:'/packageJ/eyeDevice/eyeDeviceIndex/eyeDeviceIndex?connected=' + this.data.connected
                })
              }, 800);
              // wx.redirectTo({
              //   delta: '/packageJ/eyeDevice/eyeDeviceIndex/eyeDeviceIndex?connected=' + this.data.connected
              // })
            } else if (bleData.status == 1) {
              let payload = bleData.data //对应协议中的payload数据，可以自行解析该数据
              // console.log('ddddddddd', payload)
              // console.log(ab2hex(payload, 'ab2hex'))
              // console.log(ab2hex(bleData.completeData, ' '))
              switch (payload[0]) {
                case 8:
                  console.log('8关闭设备', payload)
                  break
                case 5:
                  console.log('5启动设备', payload)
                  break
                case 2:
                  // console.log('查询设备状态', payload)
                  let json = {
                    0: '上报状态' + payload[0],
                    1: '工作状态' + payload[1],
                    2: '佩戴状态' + payload[2],
                    3: '模式' + payload[3],
                    4: '强度' + payload[4],
                    5: '温度' + payload[5],
                    6: '工作总时间' + payload[6],
                    7: '剩余工作时间' + payload[7] + '/' + payload[8],
                    8: '语音' + payload[9],
                  }
                  console.log('2', json)
                  break
                case 4:
                  console.log('4查询设备状态', payload)
                  break
              }
              // const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
              // let data = {}
              // if (idx === -1) {
              //   data[`chs[${this.data.chs.length}]`] = {
              //     uuid: characteristic.characteristicId,
              //     value: ab2hex(bleData.completeData, ' ')
              //   }
              // } else {
              //   data[`chs[${idx}]`] = {
              //     uuid: characteristic.characteristicId,
              //     value: ab2hex(bleData.completeData, ' ')
              //   }
              // }
              // this.setData(data)
            } else {}
          })
        },
        fail(res) {
          wx.hideLoading()
          wx.showToast({
            title: '连接失败',
            icon: 'none',
            duration: 1000
          })
          console.error('getBLEDeviceCharacteristics', res)
        }
      })
    },
    onBLEConnectionStateChange() {
      wx.onBLEConnectionStateChange((res) => {
        console.log('wx.onBLEConnectionStateChange() ', res.deviceId, res.connected, res.errorCode, res.errorMsg)
        // 该方法回调中可以用于处理连接意外断开等异常情况
        if (!res.connected) {
          wx.showToast({
            title: '连接已断开',
            icon: 'none'
          })
          this.setData({
            connected: false,
          })
          if (this.data.timeOut) {
            this.data.timeOut = null;
            clearTimeout(this.data.timeOut);
            console.log('倒计时结束',this.data.timeOut);
          }
        } else {
          this.setData({
            connected: true
          })
        }
      })
    },
    bindling(sn, mac, key) {
      let urlStr
      urlStr = app.getNetAddresss("plugin.eye-device.frontend.modules.device.controllers.bound.binding");

      app._getNetWork({
        url: urlStr,
        data: {
          device_sn: sn,
          device_address: mac ? mac : ''
        },
        success: (resdata) => {
          let res = resdata.data
          if (res.result == 1) {}
        },
        fail: function (res) {}
      });
    },
    getData() {
      this.setData({
        devices: []
      })
      let urlStr = app.getNetAddresss("plugin.eye-device.frontend.modules.device.controllers.records.index");
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data
          if (res.result == 1) {
            // let arrO = [...this.data.devices, ...res.data.data]
            // this.setData({
            //   devices: arrO
            // })
          }
        },
      });
    },
    process(arr) {
      // 缓存用于记录
      const cache = [];
      for (const t of arr) {
        // 检查缓存中是否已经存在
        if (cache.find(c => c.deviceId == t.deviceId)) {
          // 已经存在说明以前记录过，现在这个就是多余的，直接忽略
          continue;
        }
        // 不存在就说明以前没遇到过，把它记录下来
        cache.push(t);
      }

      // 记录结果就是过滤后的结果
      console.log(cache)
      return cache;
    },
  }
})